package com.projectx.dao;

import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.projectx.entity.UserData;

import org.litepal.LitePal;

import java.util.List;

public class UserDataDao {

    /**
     * 查找数据库中是否存在该用户
     * @param username
     * @return
     */
    public boolean userExist(String username) {
        List<UserData> user = LitePal.where("username = ?",username).find(UserData.class);
        return !user.isEmpty();
    }

    /**
     * 添加一组用户名和密码
     * @param username
     * @param password
     * @param login 是否正在登录
     * @return
     */
    public boolean addUser(String username,String password,boolean login){
        UserData userData = new UserData();
        userData.setUsername(username);
        userData.setPassword(password);
        userData.setLogin(login);
        return userData.save();
    }

    /**
     *更改数据库中保存的密码，核查密码交给网络
     * @param username
     * @param newPassword
     * @return
     */
    public boolean changePassword(String username,String newPassword) {
        List<UserData> user = LitePal.where("username = ?",username).find(UserData.class);
        if (user.isEmpty()) {
            return false;//用户名不存在
        } else {
            user.get(0).setPassword(newPassword);
            user.get(0).save();
            return true;
        }
    }

    /**
     * 从数据库中删除账户
     * @param username
     */
    public void deleteUser(String username) {
        LitePal.deleteAll(UserData.class,"username = ?",username);
    }

    /**
     * 从数据库中注销账户
     * @param username
     */
    public void logoutUser(String username){
        List<UserData> list = LitePal.where("username = ?", username).find(UserData.class);
        if (list.isEmpty()){
            return;
        }
//        Log.d("kmh", "logoutUser: " + "非空");
        UserData userData = list.get(0);
        userData.setToDefault("login");
        userData.updateAll("username = ?",username);
    }
}
